from PIL import Image, ImageTk

def load_and_resize_image(image_path, target_width, target_height):
    # 打开图片文件
    img = Image.open(image_path)
    
    # 计算缩放比例
    # aspect_ratio = img.width / img.height
    # new_width = window_width
    # new_height = int(new_width / aspect_ratio)
    
    # 如果新高度大于窗口高度，重新计算宽度和高度
    # if new_height > window_height:
    #     new_height = window_height
    #     new_width = int(new_height * aspect_ratio)

    # 计算图像的宽高比
    aspect_ratio = img.width / img.height
    target_aspect_ratio = target_width / target_height
    
    if aspect_ratio > target_aspect_ratio:
        # 如果当前图片宽高比大于目标宽高比
        new_height = target_height
        new_width = int(aspect_ratio * target_height)
    else:
        # 如果当前图片宽高比小于或等于目标宽高比
        new_width = target_width
        new_height = int(target_width / aspect_ratio)

    # 调整图片尺寸
    img = img.resize((new_width, new_height), Image.LANCZOS)
    
    # 将PIL图片转换为Tkinter图片
    img_tk = ImageTk.PhotoImage(img)
    
    return img_tk

# from PIL import Image

# def resize_image(image_path, output_path, target_width, target_height):
#     # 打开图片
#     img = Image.open(image_path)

#     # 计算图像的宽高比
#     aspect_ratio = img.width / img.height
#     target_aspect_ratio = target_width / target_height
    
#     if aspect_ratio > target_aspect_ratio:
#         # 如果当前图片宽高比大于目标宽高比
#         new_height = target_height
#         new_width = int(aspect_ratio * target_height)
#     else:
#         # 如果当前图片宽高比小于或等于目标宽高比
#         new_width = target_width
#         new_height = int(target_width / aspect_ratio)
    
#     # 调整图片大小
#     img = img.resize((new_width, new_height), Image.ANTIALIAS)

#     # 保存图片
#     img.save(output_path)
    
# # 使用示例
# resize_image('input.jpg', 'output.jpg', 800, 600)